import web
import hashlib
import datetime


db = web.database(dbn='mysql', db='casmrt2', user='toto', passwd='toto14')

def validate_ticket(service,ticket,username):
    try:
        test = db.select('tickets', where='ticket=$ticket and service=$service and username=$username', vars=locals())[0]
        if (test['id']):
            update_ticket(test['id'])
            return (0==0)
        else:
            return (1==0)
 
    except IndexError:
        return (1==0)



def get_tickets():
    return db.select('tickets', order='id DESC')

def get_ticket_by_id(id):
    try:
        return db.select('tickets', where='id=$id', vars=locals())[0]
    except IndexError:
        return None

def get_ticket_by_st(ticket):
    try:
        return db.select('tickets', where='ticket=$ticket', vars=locals())[0]
    except IndexError:
        return None

def update_ticket(id):
    time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    db.update('tickets', where="id=$id", vars=locals(),consumed=time)

def insert_ticket(username='toto',service='http://mrt2.blogdns.org/grr/',client_hostname='localhost',type='ServiceTicket'):
    m = hashlib.md5()
    m.update(username+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    temp = m.hexdigest()
    ticket='ST-'+temp
    time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    db.insert('tickets', id=None, ticket=ticket, service=service,created_on=time,client_hostname=client_hostname,username=username,type=type)
    return ticket

def session_has_key(key):
    try:
        test = db.select('sessions', where='cle=$key', vars=locals())[0]
        return (1==1)
    except IndexError:
        return (1==0)

def set_session(key,value):
    id = None
    if (session_has_key(key)):
        db.update('sessions', where='cle=$key', vars=locals(), value=value)
    else:
    	db.insert('sessions', id=id, cle=key, value=value)

def get_session(key):
    try:
        return db.select('sessions', where='cle=$key', vars=locals())[0]['value']
    except IndexError:
        return None


